/**
 * \* Created with IntelliJ IDEA.
 * \* User: 冯若航
 * \* Date: 2021/5/6
 * \* Time: 20:32
 * \* To change this template use File | Settings | File Templates.
 * \* Description:
 * \
 */
public class 二叉搜索树的最近公共祖先 {
     public class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;

         TreeNode(int x) {
             val = x;
         }
     }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ancestor=root;
        while (true){
            if(p.val<ancestor.val&&q.val<ancestor.val){
                ancestor=ancestor.left;
            }else if(p.val>ancestor.val&&q.val>ancestor.val){
                ancestor=ancestor.right;
            }else {
                break;
            }
        }
        return ancestor;
    }
}